<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\validate\CheckCourseware;
use think\exception\ValidateException;

// 课件池
class Courseware extends BaseController
{
    public function index()
    {
        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();
        $label = Db::name('courseware_label')->where('status', '=', 1)->field('id, title')->select();

        View::assign('cate', $cate);
        View::assign('label', $label);
        View::assign('rand', rand(11111, 99999));
        View::assign('rand1', rand(11111, 99999));
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        if (isset($get['field']) && isset($get['order'])) {
            if ( !empty($get['field']) && !empty($get['order'])) {
                $field = $get['field'];
                $sort = $get['order'];
                $order = [$field => $sort];
            } else {
                $order = ['id' => 'desc'];
            }
        } else {
            $order = ['id' => 'desc'];
        }

        $where = [];

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['a.title|a.e_title', 'like', '%'.$get['title'].'%'];
            }
        }

        if (isset($get['cate_id'])) {
            if (!empty($get['cate_id'])) {
                $where[] = ['a.cate_id', '=', $get['cate_id']];
            }
        }

        if (isset($get['label_id'])) {
            if (!empty($get['label_id'])) {
                $label_id = $get['label_id'];
                $where[] = ['','EXP',Db::raw('FIND_IN_SET("'.$label_id.'",a.label_id)')];
            }
        }


        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $where[] = ['a.type', '=', $get['type']];
            }
        }

        if (isset($get['open'])) {
            if (!empty($get['open'])) {
                $where[] = ['a.open', '=', $get['open']];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (!is_admin()) {
            $id = Db::name('courseware')->where('user_id', '<>', $this->user_id)->where('open', '=', 2)->column('id');
            $where[] = ['a.id', 'not in', $id];
        }

        $where[] = ['a.status', '=', 1];


        $total = Db::name('courseware')
            ->alias('a')
            ->join('courseware_cate b', 'b.id=a.cate_id', 'left')
            ->where($where)
            ->count();

        $rows = Db::name('courseware')
            ->alias('a')
            ->join('o_courseware_cate b', 'b.id=a.cate_id', 'left')
            ->where($where)
            ->field('a.id, a.title, a.e_title, a.cate_id, a.label_id, a.type, a.duration, a.add_time, a.open, a.user_id, a.num_of_add, b.title as cate_name')
            ->order($order)
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $label_name = Db::name('courseware_label')->where('id', 'in', $v['label_id'])->column('title');
            $v['label_name'] = implode('|', $label_name);

            $account = Db::name('admin_user')->where('id', '=', $v['user_id'])->field('givenname, surname')->find();
            $v['account'] = $account['givenname'].' '.$account['surname'];

            if (!is_admin()) {
                if ($v['user_id'] == $this->user_id) {
                    $v['ok'] = 1;
                } else {
                    $v['ok'] = 2;
                }
            } else {
                $v['ok'] = 1;
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function add()
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();
        $label = Db::name('courseware_label')->where('status', '=', 1)->field('id, title')->select();

        View::assign('cate', $cate);
        View::assign('label', $label);
        return View::fetch();
    }


    public function save(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCourseware::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {

            $data = array(
                'title'         => $this->str_delete($post['title']),
                'e_title'       => $this->str_delete($post['e_title']),
                'download'      => $post['download'],
                'cate_id'       => $post['cate_id'],
                'label_id'      => $post['label_id'],
                'open'          => $post['open'],
                'type'          => $post['type'],
                'duration' => $post['duration']*60,
                'user_id' => $this->user_id,
                'status'        => 1,
                'add_time'    => time(),
                'update_time' => time(),
            );


            if ($post['type'] == 2) {   //+文档

                if (empty($post['path'])) {
                    return $this->outputAjax('请上传附件！');
                }

                $data['path'] = $post['path'];

            } elseif ($post['type'] == 1) { //+图文

                if (empty($post['content'])) {
                    return $this->outputAjax('请填写相关内容！');
                }

                $data['content'] = $post['content'];
            } elseif ($post['type'] == 5) {
                if (empty($post['link_url'])) {
                    return $this->outputAjax('请填写外部链接！');
                }

                $data['link_url'] = $post['link_url'];
            }

            if (!Db::name('courseware')->insert($data)) {
                return $this->outputAjax('操作失败！');
            }

            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    //+删除特殊字符
    protected function str_delete($str)
    {
        return preg_replace("/[\':*?]|\]|\[|\/|\\\|\"|\|/",'',$str);
    }


    public function edit(Request $request)
    {
        if(!check_jurisdiction1(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $id = $request->get('id');

        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();

        $inf = Db::name('courseware')->where('id', '=', $id)->find();

        $label = Db::name('courseware_label')->where('status', '=', 1)->where('id', 'not in', $inf['label_id'])->field('id, title')->select();
        $label1 = Db::name('courseware_label')->where('status', '=', 1)->where('id', 'in', $inf['label_id'])->field('id, title')->select();
        View::assign('inf', $inf);
        View::assign('cate', $cate);
        View::assign('label', $label);
        View::assign('label1', $label1);
        return View::fetch();
    }


    public function modify(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();
        $post = remove_xss($post);

        // 验证
        try {

            validate(CheckCourseware::class)->check($post);

        } catch (ValidateException $e) {

            return $this->outputAjax($e->getError());
        }

        try {

            $data = array(
                'id'         => $post['id'],
                'title'         => $this->str_delete($post['title']),
                'e_title'       => $this->str_delete($post['e_title']),
                'download'      => $post['download'],
                'cate_id'       => $post['cate_id'],
                'label_id'      => $post['label_id'],
                'open'          => $post['open'],
                'duration' => $post['duration']*60,
                'update_time' => time(),
            );


            if ($post['type'] == 2) {   //+文档

                if (empty($post['path'])) {
                    return $this->outputAjax('请上传附件！');
                }

                $data['path'] = $post['path'];

            } elseif ($post['type'] == 1) { //+图文

                if (empty($post['content'])) {
                    return $this->outputAjax('请填写相关内容！');
                }

                $data['content'] = $post['content'];
            } elseif ($post['type'] == 5) {
                if (empty($post['link_url'])) {
                    return $this->outputAjax('请填写外部链接！');
                }

                $data['link_url'] = $post['link_url'];
            }

            if (!Db::name('courseware')->update($data)) {
                return $this->outputAjax('操作失败！');
            }

            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 课件复制
    public function copy(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        $inf = Db::name('courseware')->where('id', '=', $id)->find();

        if (!$inf) {
            return $this->outputAjax('参数错误');
        }

        try {
            $data = array(
                'title'         => $inf['title'],
                'e_title'       => $inf['e_title'],
                'download'      => $inf['download'],
                'cate_id'       => $inf['cate_id'],
                'label_id'      => $inf['label_id'],
                'open'          => $inf['open'],
                'duration' => $inf['duration'],
                'content' => $inf['content'],
                'link_url' => $inf['link_url'],
                'path' => $inf['path'],
                'status' => $inf['status'],
                'type' => $inf['type'],
                'user_id' => $this->user_id,
                'update_time' => time(),
                'add_time' => time(),
            );
            $courseware_id = Db::name('courseware')->insertGetId($data);
            if (!$courseware_id) {
                return $this->outputAjax('操作失败！');
            }

            if ($inf['type'] == 4) {
                $survey = Db::name('courseware_survey')
                    ->where('courseware_id', '=', $inf['id'])
                    ->find();

                $insert = array(
                    'courseware_id' => $courseware_id,
                    'title' => $survey['title'],
                    'e_title' => $survey['e_title'],
                    'images' => $survey['images'],
                    'description' => $survey['description'],
                    'survey_result' => $survey['survey_result'],
                    'end_time' => $survey['end_time'],
                    'relation' => $survey['relation'],
                    'add_time' => time(),
                    'update_time' => time(),
                );
                $survey_id = Db::name('courseware_survey')->insertGetId($insert);
                if (!$survey_id) {
                    return $this->outputAjax('操作失败[1]');
                }

                $subject = Db::name('courseware_survey_subject')
                    ->where('survey_id', '=', $survey['id'])
                    ->select()
                    ->toArray();

                foreach ($subject as &$val) {
                    $insert = array(
                        'survey_id' => $survey_id,
                        'subject' => $val['subject'],
                        'images' => $val['images'],
                        'other' => $val['other'],
                        'min' => $val['min'],
                        'max' => $val['max'],
                        'character_min' => $val['character_min'],
                        'character_max' => $val['character_max'],
                        'height' => $val['height'],
                        'subject_type' => $val['subject_type'],
                        'one_intro' => $val['one_intro'],
                        'ten_intro' => $val['ten_intro'],
                        'add_time' => time(),
                        'update_time' => time(),
                    );
                    $subject_id = Db::name('courseware_survey_subject')->insertGetId($insert);
                    if (!$subject_id) {
                        return $this->outputAjax('操作失败[2]');
                    }

                    $option = Db::name('courseware_survey_option')
                        ->where('survey_id', '=', $val['survey_id'])
                        ->where('subject_id', '=', $val['id'])
                        ->select()
                        ->toArray();

                    foreach ($option as &$value) {
                        $insert = array(
                            'survey_id' => $survey_id,
                            'subject_id' => $subject_id,
                            'title' => $value['title'],
                            'option_images' => $value['option_images'],
                            'letter' => $value['letter'],
                            'update_time' => time(),
                        );
                        if (!Db::name('courseware_survey_option')->insert($insert)) {
                            return $this->outputAjax('操作失败[3]');
                        }
                    }
                }
            } else if ($inf['type'] == 3) {
                $test = Db::name('courseware_test')
                    ->where('courseware_id', '=', $inf['id'])
                    ->find();

                if ($test) {
                    $insert = array(
                        'courseware_id' => $courseware_id,
                        'title' => $test['title'],
                        'e_title' => $test['e_title'],
                        'is_duration' => $test['is_duration'],
                        'duration' => $test['duration'],
                        'limits' => $test['limits'],
                        'score' => $test['score'],
                        'fpy' => $test['fpy'],
                        'is_number' => $test['is_number'],
                        'number' => $test['number'],
                        'is_number_read' => $test['is_number_read'],
                        'sum_score' => $test['sum_score'],
                        'add_time' => time(),
                    );
                    $test_id = Db::name('courseware_test')->insertGetId($insert);
                    if (!$test_id) {
                        return $this->outputAjax('操作失败[4]');
                    }

                    $question = Db::name('courseware_test_question')
                        ->where('test_id', '=', $test['id'])
                        ->select()
                        ->toArray();

                    foreach ($question as &$qv) {
                        $insert = array(
                            'test_id' => $test_id,
                            'title' => $qv['title'],
                            'q_score' => $qv['q_score'],
                            'img' => $qv['img'],
                            'a_type' => $qv['a_type'],
                            'check' => $qv['check'],
                            'remark' => $qv['remark'],
                            'answer' => $qv['answer'],
                            'add_time' => time(),
                        );
                        if (!Db::name('courseware_test_question')->insert($insert)) {
                            return $this->outputAjax('操作失败[5]');
                        }
                    }
                }
            }

            return $this->outputAjax('操作成功！',0);

        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $id = $request->post('id');

        try {

            $num_of_add = Db::name('courseware')->where('id', '=', $id)->value('num_of_add');
            if ($num_of_add > 0) {
                return $this->outputAjax('删除失败, 该课件已被添加至课程！');
            }

            if (!Db::name('courseware')->where('id', '=', $id)->update(['status' => 3])) {
                return $this->outputAjax('删除失败！');
            }
            return $this->outputAjax('删除成功！',0);
        } catch (\Exception $e) {
            return $this->outputAjax($e->getMessage());
        }
    }


    // 测试课件
    public function test(Request $request)
    {

        $id = $request->param('id');

        if($id) {

            $data = Db::name('courseware')->where('id', '=', $id)->find();
            $jsonArr = json_decode($data['content'],true);
            $jsonArr['title'] = str_replace(array("\r\n", "\r", "\n","\t"), "", htmlspecialchars_decode($jsonArr['title']));
            $jsonArr['title'] = str_replace(array("'"), "＇", htmlspecialchars_decode($jsonArr['title']));
            $jsonArr['title'] = str_replace(array("\""), "＂", htmlspecialchars_decode($jsonArr['title']));
            $jsonArr['title'] = str_replace(array("\\"), "＼", htmlspecialchars_decode($jsonArr['title']));
            $jsonArr['title'] = str_replace(array("  "), " ", htmlspecialchars_decode($jsonArr['title']));

            if (isset($jsonArr['e_title'])) {
                $jsonArr['e_title'] = str_replace(array("\r\n", "\r", "\n","\t"), "", htmlspecialchars_decode($jsonArr['e_title']));
                $jsonArr['e_title'] = str_replace(array("'"), "＇", htmlspecialchars_decode($jsonArr['e_title']));
                $jsonArr['e_title'] = str_replace(array("\""), "＂", htmlspecialchars_decode($jsonArr['e_title']));
                $jsonArr['e_title'] = str_replace(array("\\"), "＼", htmlspecialchars_decode($jsonArr['e_title']));
                $jsonArr['e_title'] = str_replace(array("  "), " ", htmlspecialchars_decode($jsonArr['e_title']));
            }

            $test_id = Db::name('courseware_test')->where('courseware_id', '=', $data['id'])->value('id');

            $question = Db::name('courseware_test_question')
                ->field('id, q_score as s, title as t, img as i, a_type, check, remark, answer as a')
                ->where('test_id', '=', $test_id)
                ->select()
                ->toArray();


            foreach ($question as &$value) {

                $value['t'] = str_replace(array("\r\n", "\r", "\n","\t"), "", htmlspecialchars_decode($value['t']));
                $value['t'] = str_replace(array("'"), "＇", htmlspecialchars_decode($value['t']));
                $value['t'] = str_replace(array("\""), "＂", htmlspecialchars_decode($value['t']));
                $value['t'] = str_replace(array("\\"), "＼", htmlspecialchars_decode($value['t']));
                $value['t'] = str_replace(array("  "), " ", htmlspecialchars_decode($value['t']));
                $arr = json_decode($value['a'],true);

                foreach ($arr as &$v) {
                    $v['t'] = str_replace(array("\r\n", "\r", "\n","\t"), "", htmlspecialchars_decode($v['t']));
                    $v['t'] = str_replace(array("'"), "＇", htmlspecialchars_decode($v['t']));
                    $v['t'] = str_replace(array("\""), "＂", htmlspecialchars_decode($v['t']));
                    $v['t'] = str_replace(array("\\"), "＼", htmlspecialchars_decode($v['t']));
                    $v['t'] = str_replace(array("   "), " ", htmlspecialchars_decode($v['t']));
                }

                $value['a'] = $arr;
            }

            $jsonArr['id'] = $id;
            $jsonArr['question'] = $question;
            $data['content'] = json_encode($jsonArr, JSON_UNESCAPED_UNICODE);

            View::assign('data', $data);
            View::assign('content', json_encode($jsonArr, JSON_UNESCAPED_UNICODE));
            View::assign('test_id', $test_id);

        } else {
            View::assign('content', json_encode([], JSON_UNESCAPED_UNICODE));
        }

        if($id) {
            $label = Db::name('courseware_label')->where('status', '=', 1)->where('id', 'not in', $data['label_id'])->field('id, title')->select();
            $label1 = Db::name('courseware_label')->where('status', '=', 1)->where('id', 'in', $data['label_id'])->field('id, title')->select();
            View::assign('label', $label);
            View::assign('label1', $label1);
        } else {
            $label = Db::name('courseware_label')->where('status', '=', 1)->field('id, title')->select();
            View::assign('label', $label);
            View::assign('label1', []);
        }


        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();
        View::assign('cate', $cate);

        View::assign('id', $id);
        return View::fetch();
    }


    public function saveTest(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $data = $request->post();


        //各种判断数据 htmlspecialchars

        $id = $data['id'];



        Db::startTrans();
        try {
            $courseware = [
                'type' => 3, // 1 2 3 4 -- 3:答题测试
                'cate_id'       => $data['cate_id'],
                'label_id'      => $data['label_id'],
                'open'          => $data['open'],
                'duration' => 0,
                'user_id' => $this->user_id,
                'status'        => 1,
                'title' => $data['title'],
                'e_title' => $data['e_title'],
                'content' => json_encode($data, JSON_UNESCAPED_UNICODE),
                'path' => '',
                'update_time' => time()
            ];

            if ($id) {

                $res = Db::name('courseware')->where('id', '=', $id)->update($courseware);
                if (!$res) {
                    Db::rollback();
                    return $this->outputAjax('数据写入失败[1]');
                }
                $courseware_id = $id;
            } else {

                $courseware['add_time'] = time();
                $courseware_id = Db::name('courseware')->insertGetId($courseware);
                if (!$courseware_id) {
                    Db::rollback();
                    return $this->outputAjax('数据写入失败[2]');
                }
            }


            //测试数据
            $testData = [
                'title' => $data['title'],
                'e_title' => $data['e_title'],
                'is_duration' => $data['is_duration'],
                'duration' => $data['duration'],
                'limits' => $data['limit'],
                'score' => $data['score'],
                'fpy' => $data['fpy'],
                'is_number' => $data['is_number'],
                'number' => $data['number'],
                'is_number_read' => $data['is_number_read'],
                'sum_score' => $data['sum_score'],
            ];


            if ($id) {
                $testData['update_time'] = time();

                //测试模块
                $res = Db::name('courseware_test')->where('courseware_id', '=', $courseware_id)->update($testData);
                if (!$res) {
                    Db::rollback();
                    return $this->outputAjax('数据写入失败[3]');
                }
                $test_id = Db::name('courseware_test')->where('courseware_id', '=', $courseware_id)->value('id');

            } else {

                //测试模块
                $testData['courseware_id'] = $courseware_id;
                $testData['add_time'] = time();
                $test_id = Db::name('courseware_test')->insertGetId($testData);
                if (!$test_id) {
                    Db::rollback();
                    return $this->outputAjax('数据写入失败[5]');
                }

            }

            //查询已存在的所有问题id
            $questionIds = Db::name('courseware_test_question')->where('test_id', '=', $test_id)->column('id');
            //处理问题
            foreach ($data['question'] as $key => $value) {
                # code...
                $questionData = [
                    'title' => $value['t'],
                    'q_score' => $value['s'],
                    'img' => $value['i'],
                    'a_type' => $value['a_type'],
                    'check' => $value['check'],
                    'remark' => $value['remark'],
                    'answer' => json_encode($value['a'], JSON_UNESCAPED_UNICODE),
                    'test_id' => $test_id,
                ];
                if (isset($value['id']) && $value['id'] > 0) {
                    $questionData['update_time'] = time();
                    //更新
                    foreach ($questionIds as $k => $v) {
                        if($v == $value['id']) unset($questionIds[$k]);
                    }
                    $q_res = Db::name('courseware_test_question')->where('id', '=', $value['id'])->update($questionData);
                } else {
                    //新增
                    $questionData['add_time'] = time();
                    $q_res = Db::name('courseware_test_question')->insert($questionData);
                }

                if ($q_res === false) {

                    Db::rollback();
                    return $this->outputAjax('问题数据写入失败[1]');

                }
            }

            //删除删除的问题
            if (count($questionIds) > 0) {
                $res = Db::name('courseware_test_question')->where('id', 'in', $questionIds)->delete();
                if (!$res) {
                    Db::rollback();
                    return $this->outputAjax('删除删除的问题失败[3]');
                }
            }


            Db::commit();
            return $this->outputAjax('保存成功', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }

    }


    // 调研
    public function survey()
    {
        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();
        $label = Db::name('courseware_label')->where('status', '=', 1)->field('id, title')->select();

        View::assign('cate', $cate);
        View::assign('label', $label);

        return View::fetch();
    }

    // 新增调研
    public function saveSurvey(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post['subject'])) {
            return $this->outputAjax('请填写问题');
        }

        $data = $post['data'];

        Db::startTrans();

        try {
            $courseware = [
                'title' => $data['title'],
                'e_title' => $data['e_title'],
                'type' => 4, // 1 2 3 4 -- 4:survey
                'cate_id'       => $data['cate_id'],
                'label_id'      => $data['label_id'],
                'open'          => $data['open'],
                'duration' => 0,
                'user_id' => $this->user_id,
                'status'        => 1,
                'content' => '',
                'path' => '',
                'add_time' => time(),
                'update_time' => time()
            ];

            $id = Db::name('courseware')->insertGetId($courseware);

            if (!$id) {
                return $this->outputAjax('保存失败[1]');
            }

            $survey = array(
                'courseware_id' => $id,
                'title' => $data['title'],
                'e_title' => $data['e_title'],
                'images' => $data['images'],
                'description' => $data['description'],
                'survey_result' => $data['survey_result'],
                'end_time' => strtotime($data['end_time']),
                'relation' => $data['relation'],
                'add_time' => time(),
            );

            $survey_id = Db::name('courseware_survey')->insertGetId($survey);

            if (!$survey_id) {
                Db::rollback();
                return $this->outputAjax('保存失败[2]');
            }


            foreach ($post['subject'] as $key => $val) {

                $subject = array(
                    'survey_id' => $survey_id,
                    'subject' => $val['subject'],
                    'subject_type' => 1,
                    'add_time' => time()
                );

                if (isset($val['images'])!= false) {
                    $subject['images'] = $val['images'];
                }

                if (isset($val['other'])!= false) {
                    $subject['other'] = $val['other'];
                }

                if (isset($val['min'])!= false && isset($val['max'])!= false) {
                    if (isset($val['other'])!= false) {
                        $option_count = count($val['options'])+1;
                    } else {
                        $option_count = count($val['options']);
                    }
                    if ($val['min'] > $option_count || $val['max'] > $option_count) {
                        Db::rollback();
                        return $this->outputAjax('问题['.($key+1).']答题选择数量超过选项数, 请检查');
                    }
                    $subject['min'] = $val['min'];
                    $subject['max'] = $val['max'];
                    $subject['subject_type'] = 2;
                }


                if (isset($val['character_min'])!= false && isset($val['character_max'])!= false && isset($val['height'])!= false) {
                    $subject['character_min'] = $val['character_min'];
                    $subject['character_max'] = $val['character_max'];
                    $subject['height'] = $val['height'] == ''? 3 : $val['height'];
                    $subject['subject_type'] = 3;
                }

                if (isset($val['one_intro'])!= false && isset($val['ten_intro'])!= false) {
                    $subject['one_intro'] = $val['one_intro'] == '' ? '不可能' : $val['one_intro'];
                    $subject['ten_intro'] = $val['ten_intro'] == '' ? '极有可能' : $val['ten_intro'];
                    $subject['subject_type'] = 4;
                }


                if ($subject['subject_type'] == 1 || $subject['subject_type'] == 2) {
                    if (empty($val['options'])) {
                        Db::rollback();
                        return $this->outputAjax('请填写选项');
                    }

                }

                $subject_id = Db::name('courseware_survey_subject')->insertGetId($subject);
                if (!$subject_id) {
                    Db::rollback();
                    return $this->outputAjax('保存失败[3]');
                }

                if ($subject['subject_type'] == 1 || $subject['subject_type'] == 2) {
                    $xuanxiang = [];
                    foreach ($val['options'] as &$value) {
                        array_push($xuanxiang, $value['option']);
                    }
                    if (count($xuanxiang) != count(array_unique($xuanxiang))) {
                        Db::rollback();
                        return $this->outputAjax('问题['.($key+1).']有重复选项, 请检查');
                    }
                    foreach ($val['options'] as $k => $v) {
                        if ($v['option'] == '') {
                            Db::rollback();
                            return $this->outputAjax('选项不得为空');
                        }
                        $option = array(
                            'survey_id' => $survey_id,
                            'subject_id' => $subject_id,
                            'title' => $v['option'],
                            'letter' => $this->letter($k)
                        );
                        if (isset($v['option_images'])!= false) {
                            $option['option_images'] = $v['option_images'];
                        }

                        $option_id = Db::name('courseware_survey_option')->insertGetId($option);

                        if (!$option_id) {
                            Db::rollback();
                            return $this->outputAjax('保存失败[4]');
                        }
                    }
                } else if ($subject['subject_type'] == 4) {
                    $option = array(
                        array(
                            'survey_id' => $survey_id,
                            'subject_id' => $subject_id,
                            'title' => 'NA',
                            'letter' => 'A',
                            'option_images' => '',
                            'update_time' => time()
                        )
                    );

                    for ($i = 0; $i < 10; $i += 1) {
                        $arr = array(
                            'survey_id' => $survey_id,
                            'subject_id' => $subject_id,
                            'title' => $i+1,
                            'letter' => $this->letter($i+1),
                            'option_images' => '',
                            'update_time' => time()
                        );
                        array_push($option, $arr);
                    }

                    $option_id = Db::name('courseware_survey_option')->insertAll($option);

                    if (!$option_id) {
                        Db::rollback();
                        return $this->outputAjax('保存失败[5]');
                    }
                }
            }
            Db::commit();
            return $this->outputAjax('保存成功', 0);

        } catch (\Exception $e) {
            Db::rollback();
            return $this->outputAjax($e->getMessage());
        }
    }

    protected function letter($key)
    {
        $data = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE'];
        return $data[$key];
    }


    public function editSurvey(Request $request)
    {
        $id = $request->get('id');

        $courseware = Db::name('courseware')
            ->where('id', '=', $id)
            ->find();


        $survey = Db::name('courseware_survey')
            ->where('courseware_id', '=', $courseware['id'])
            ->find();


        $subject = Db::name('courseware_survey_subject')
            ->where('survey_id', '=', $survey['id'])
            ->select()
            ->toArray();

        foreach ($subject as &$v) {
            $option = Db::name('courseware_survey_option')
                ->where('subject_id', '=', $v['id'])
                ->select()
                ->toArray();

            $v['options'] = $option;
            $v['options_count'] = count($option);
        }

        $survey['subject'] = $subject;
        $survey['subject_count'] = count($subject);
        $survey['end_time'] = $survey['end_time'] != '' ? date('Y-m-d H:i:s', $survey['end_time']):'';

        View::assign('survey', $survey);
        View::assign('courseware_id', $courseware['id']);
        View::assign('courseware', $courseware);


        $cate = Db::name('courseware_cate')->where('status', '=', 1)->field('id, title')->select();

        $label = Db::name('courseware_label')->where('status', '=', 1)->where('id', 'not in', $courseware['label_id'])->field('id, title')->select();
        $label1 = Db::name('courseware_label')->where('status', '=', 1)->where('id', 'in', $courseware['label_id'])->field('id, title')->select();

        View::assign('cate', $cate);
        View::assign('label', $label);
        View::assign('label1', $label1);

        $res = Db::name('survey_answer')
            ->where('survey_id', '=', $survey['id'])
            ->find();
        if ($res) {
            return View::fetch('courseware/edit_survey1');
        } else {
            return View::fetch('courseware/edit_survey');
        }
    }

    // 修改survey
    public function modifySurvey(Request $request)
    {

        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }

        $post = $request->post();

        if (empty($post['subject'])) {
            return $this->outputAjax('请填写问题');
        }

        $data = $post['data'];

        Db::startTrans();

        $courseware = [
            'id' => $data['courseware_id'],
            'title' => $data['title'],
            'e_title' => $data['e_title'],
            'cate_id'       => $data['cate_id'],
            'label_id'      => $data['label_id'],
            'open'          => $data['open'],
            'update_time' => time()
        ];
        if (!Db::name('courseware')->update($courseware)) {
            Db::rollback();
            return $this->outputAjax('保存失败[1]');
        }

        $survey = array(
            'id' => $data['id'],
            'title' => $data['title'],
            'e_title' => $data['e_title'],
            'images' => $data['images'],
            'description' => $data['description'],
            'survey_result' => $data['survey_result'],
            'end_time' => strtotime($data['end_time']),
            'relation' => $data['relation'],
            'update_time' => time()
        );

        if (!Db::name('courseware_survey')->update($survey)) {
            Db::rollback();
            return $this->outputAjax('保存失败[2]');
        }

        $old_subject = Db::name('courseware_survey_subject')->where('survey_id', '=', $data['id'])->column('id');
        $new_subject = [];
        foreach ($post['subject'] as $key => $val) {
            array_push($new_subject, $val['id']);

            if ($val['id'] == 0) {
                $subject = array(
                    'survey_id' => $data['id'],
                    'subject' => $val['subject'],
                    'subject_type' => 1,
                    'add_time' => time()
                );

                if (isset($val['images']) != false) {
                    $subject['images'] = $val['images'];
                }
                if (isset($val['other']) != false) {
                    $subject['other'] = $val['other'];
                }
                if (isset($val['min'])!= false && isset($val['max'])!= false) {
                    if (isset($val['other'])!= false) {
                        $option_count = count($val['options'])+1;
                    } else {
                        $option_count = count($val['options']);
                    }
                    if ($val['min'] > $option_count || $val['max'] > $option_count) {
                        Db::rollback();
                        return $this->outputAjax('问题['.($key+1).']答题选择数量超过选项数, 请检查');
                    }
                    $subject['min'] = $val['min'];
                    $subject['max'] = $val['max'];
                    $subject['subject_type'] = 2;
                }
                if (isset($val['character_min'])!= false && isset($val['character_max'])!= false && isset($val['height'])!= false) {
                    $subject['character_min'] = $val['character_min'];
                    $subject['character_max'] = $val['character_max'];
                    $subject['height'] = $val['height'] == ''? 3 : $val['height'];
                    $subject['subject_type'] = 3;
                }

                if (isset($val['one_intro'])!= false && isset($val['ten_intro'])!= false) {
                    $subject['one_intro'] = $val['one_intro'] == '' ? '不可能' : $val['one_intro'];
                    $subject['ten_intro'] = $val['ten_intro'] == '' ? '极有可能' : $val['ten_intro'];
                    $subject['subject_type'] = 4;
                }

                if ($subject['subject_type'] == 1 || $subject['subject_type'] == 2) {
                    if (empty($val['options'])) {
                        Db::rollback();
                        return $this->outputAjax('请填写选项');
                    }
                }

                $subject_id = Db::name('courseware_survey_subject')->insertGetId($subject);
                if (!$subject_id) {
                    Db::rollback();
                    return $this->outputAjax('保存失败[3]');
                }

                if ($subject['subject_type'] == 1 || $subject['subject_type'] == 2) {
                    $xuanxiang = [];
                    foreach ($val['options'] as &$value) {
                        array_push($xuanxiang, $value['option']);
                    }
                    if (count($xuanxiang) != count(array_unique($xuanxiang))) {
                        Db::rollback();
                        return $this->outputAjax('问题['.($key+1).']有重复选项, 请检查');
                    }
                    foreach ($val['options'] as $k => $v) {
                        if ($v['option'] == '') {
                            Db::rollback();
                            return $this->outputAjax('选项不得为空');
                        }
                        $option = array(
                            'survey_id' => $data['id'],
                            'subject_id' => $subject_id,
                            'title' => $v['option'],
                            'letter' => $this->letter($k)
                        );
                        if (isset($v['option_images'])!= false) {
                            $option['option_images'] = $v['option_images'];
                        }

                        $option_id = Db::name('courseware_survey_option')->insertGetId($option);

                        if (!$option_id) {
                            Db::rollback();
                            return $this->outputAjax('保存失败[4]');
                        }
                    }
                } else if ($subject['subject_type'] == 4) {
                    $option = array(
                        array(
                            'survey_id' => $data['id'],
                            'subject_id' => $subject_id,
                            'title' => 'NA',
                            'letter' => 'A',
                            'option_images' => '',
                            'update_time' => time()
                        )
                    );

                    for ($i = 0; $i < 10; $i += 1) {
                        $arr = array(
                            'survey_id' => $data['id'],
                            'subject_id' => $subject_id,
                            'title' => $i+1,
                            'letter' => $this->letter($i+1),
                            'option_images' => '',
                            'update_time' => time()
                        );
                        array_push($option, $arr);
                    }

                    $option_id = Db::name('courseware_survey_option')->insertAll($option);

                    if (!$option_id) {
                        Db::rollback();
                        return $this->outputAjax('保存失败[5]');
                    }
                }
            } else {
                $subject = array(
                    'id' => $val['id'],
                    'subject' => $val['subject'],
                    'subject_type' => 1,
                    'images' => '',
                    'other' => '',
                    'min' => '',
                    'max' => '',
                    'character_min' => '',
                    'character_max' => '',
                    'height' => '',
                    'one_intro' => '',
                    'ten_intro' => '',
                    'update_time' => time()
                );

                if (isset($val['images']) != false) {
                    $subject['images'] = $val['images'];
                }

                if (isset($val['other']) != false) {
                    $subject['other'] = $val['other'];
                }
                if (isset($val['min'])!= false && isset($val['max'])!= false) {
                    if (isset($val['other'])!= false) {
                        $option_count = count($val['options'])+1;
                    } else {
                        $option_count = count($val['options']);
                    }
                    if ($val['min'] > $option_count || $val['max'] > $option_count) {
                        Db::rollback();
                        return $this->outputAjax('问题['.($key+1).']答题选择数量超过选项数, 请检查');
                    }
                    $subject['min'] = $val['min'];
                    $subject['max'] = $val['max'];
                    $subject['subject_type'] = 2;
                }

                if (isset($val['character_min'])!= false && isset($val['character_max'])!= false && isset($val['height'])!= false) {
                    $subject['character_min'] = $val['character_min'];
                    $subject['character_max'] = $val['character_max'];
                    $subject['height'] = $val['height'] == ''? 3 : $val['height'];
                    $subject['subject_type'] = 3;
                }

                if (isset($val['one_intro'])!= false && isset($val['ten_intro'])!= false) {
                    $subject['one_intro'] = $val['one_intro'] == '' ? '不可能' : $val['one_intro'];
                    $subject['ten_intro'] = $val['ten_intro'] == '' ? '极有可能' : $val['ten_intro'];
                    $subject['subject_type'] = 4;
                }

                if ($subject['subject_type'] == 1 || $subject['subject_type'] == 2) {
                    if (empty($val['options'])) {
                        Db::rollback();
                        return $this->outputAjax('请填写选项');
                    }
                }
                if (!Db::name('courseware_survey_subject')->update($subject)) {
                    Db::rollback();
                    return $this->outputAjax('保存失败[3]');
                }

                if ($subject['subject_type'] == 3) {
                    $res = Db::name('courseware_survey_option')->where('subject_id', '=', $val['id'])->find();
                    if ($res) {
                        if (!Db::name('courseware_survey_option')->where('subject_id', '=', $val['id'])->delete()) {
                            Db::rollback();
                            return $this->outputAjax('保存失败[3.1]');
                        }
                    }
                } else if ($subject['subject_type'] == 4) {
                    $res = Db::name('courseware_survey_option')->where('subject_id', '=', $val['id'])->find();
                    if (!$res) {
                        $option = array(
                            array(
                                'survey_id' => $data['id'],
                                'subject_id' => $val['id'],
                                'title' => 'NA',
                                'letter' => 'A',
                                'option_images' => '',
                                'update_time' => time()
                            )
                        );

                        for ($i = 0; $i < 10; $i += 1) {
                            $arr = array(
                                'survey_id' => $data['id'],
                                'subject_id' => $val['id'],
                                'title' => $i+1,
                                'letter' => $this->letter($i+1),
                                'option_images' => '',
                                'update_time' => time()
                            );
                            array_push($option, $arr);
                        }

                        $option_id = Db::name('courseware_survey_option')->insertAll($option);

                        if (!$option_id) {
                            Db::rollback();
                            return $this->outputAjax('保存失败[3.3]');
                        }
                    }
                }

                if ($subject['subject_type'] == 1 || $subject['subject_type'] == 2) {
                    $xuanxiang = [];
                    foreach ($val['options'] as &$value) {
                        array_push($xuanxiang, $value['option']);
                    }
                    if (count($xuanxiang) != count(array_unique($xuanxiang))) {
                        Db::rollback();
                        return $this->outputAjax('问题['.($key+1).']有重复选项, 请检查');
                    }
                    $old_option = Db::name('courseware_survey_option')->where('subject_id', '=', $val['id'])->column('id');
                    $new_option = [];
                    foreach ($val['options'] as $k => $v) {
                        array_push($new_option, $v['id']);
                        if ($v['option'] == '') {
                            Db::rollback();
                            return $this->outputAjax('选项不得为空');
                        }
                        if ($v['id'] == 0) {
                            $option = array(
                                'survey_id' => $data['id'],
                                'subject_id' => $val['id'],
                                'title' => $v['option'],
                                'letter' => $this->letter($k)
                            );
                            if (isset($v['option_images'])!= false) {
                                $option['option_images'] = $v['option_images'];
                            }

                            $option_id = Db::name('courseware_survey_option')->insertGetId($option);
                            if (!$option_id) {
                                Db::rollback();
                                return $this->outputAjax('保存失败[4]');
                            }
                        } else {
                            $option = array(
                                'id' => $v['id'],
                                'title' => $v['option'],
                                'letter' => $this->letter($k),
                                'update_time' => time()
                            );
                            if (isset($v['option_images'])!= false) {
                                $option['option_images'] = $v['option_images'];
                            }

                            if (!Db::name('courseware_survey_option')->update($option)) {
                                Db::rollback();
                                return $this->outputAjax('保存失败[4.1]');
                            }
                        }
                    }

                    $option_diff = array_diff($old_option, $new_option);
                    if (!empty($option_diff)) {
                        if (!Db::name('courseware_survey_option')->where('id', 'in', $option_diff)->delete()) {
                            Db::rollback();
                            return $this->outputAjax('保存失败[6]');
                        }
                    }
                }
            }
        }

        $subject_diff = array_diff($old_subject, $new_subject);
        if (!empty($subject_diff)) {
            if (!Db::name('courseware_survey_subject')->where('id', 'in', $subject_diff)->delete()) {
                Db::rollback();
                return $this->outputAjax('保存失败[7]');
            }
        }

        Db::commit();
        return $this->outputAjax('保存成功', 0);
    }


    // 数据导出
    public function export(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }


        $get = $request->get();

        $where = [];

        if (isset($get['title'])) {
            if (!empty($get['title'])) {
                $where[] = ['a.title|a.e_title', 'like', '%'.$get['title'].'%'];
            }
        }

        if (isset($get['cate_id'])) {
            if (!empty($get['cate_id'])) {
                $where[] = ['a.cate_id', '=', $get['cate_id']];
            }
        }

        if (isset($get['label_id'])) {
            if (!empty($get['label_id'])) {
                $label_id = $get['label_id'];
                $where[] = ['','EXP',Db::raw('FIND_IN_SET("'.$label_id.'",a.label_id)')];
            }
        }


        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $where[] = ['a.type', '=', $get['type']];
            }
        }

        if (isset($get['open'])) {
            if (!empty($get['open'])) {
                $where[] = ['a.open', '=', $get['open']];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (!is_admin()) {
            $id = Db::name('courseware')->where('user_id', '<>', $this->user_id)->where('open', '=', 2)->column('id');
            $where[] = ['a.id', 'not in', $id];
        }

        $where[] = ['a.status', '=', 1];

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件池数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['ID', '课件名称(CN)', '课件名称(EN)', '课件分类', '课件标签', '课件时长(分钟)', '课件类型', '是否公开', '创建人', '创建时间', '添加次数']);

        //链接数据库
        $total = Db::name('courseware')
            ->alias('a')
            ->join('o_courseware_cate b', 'b.id=a.cate_id', 'left')
            ->where($where)
            ->count();


        $nums = 2000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::name('courseware')
                ->alias('a')
                ->join('o_courseware_cate b', 'b.id=a.cate_id', 'left')
                ->where($where)
                ->field('a.id, a.title, a.e_title, a.cate_id, a.label_id, a.type, a.duration, a.add_time, a.open, a.num_of_add, a.user_id, b.title as cate_name')
                ->order('a.add_time', 'desc')
                ->limit($start, $nums)
                ->select()
                ->toArray();

            foreach ($rows as $v) {
                $label_name = Db::name('courseware_label')->where('id', 'in', $v['label_id'])->column('title');
                $label_name = implode('|', $label_name);

                $account_info = Db::name('admin_user')->where('id', '=', $v['user_id'])->field('givenname, surname')->find();
                $account = $account_info['givenname'].' '.$account_info['surname'];
                switch ($v['type']) {
                    case 1:
                        $type_name = '图文';
                        break;
                    case 2:
                        $type_name = '文档';
                        break;
                    case 3:
                        $type_name = '测试';
                        break;
                    case 4:
                        $type_name = 'Survey';
                        break;
                    case 5:
                        $type_name = '外链';
                        break;
                }

                switch ($v['open']) {
                    case 1:
                        $open_name = '公开';
                        break;
                    case 2:
                        $open_name = '非公开';
                        break;
                }

                $arr = [
                    $v['id'],
                    $v['title'],
                    $v['e_title'],
                    $v['cate_name'],
                    $label_name,
                    $v['duration']/60,
                    $type_name,
                    $open_name,
                    $account,
                    date('Y-m-d H:i',$v['add_time']),
                    $v['num_of_add']
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }


    public function classesRecord(Request $request)
    {
        $id = $request->param('id');

        View::assign('id',$id);

        return View::fetch();
    }

    // 课件班级学习记录
    public function getClassesRecordList(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['d.name|d.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['b.courseware_id', '=', $get['id']];
        $where[] = ['a.qiandao', '=', 0];


        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_classes_step_resource b', 'b.id=a.resource_id')
            ->join('o_classes c', 'c.id=a.classes_id')
            ->join('o_members d', 'd.userid=a.userid')
            ->where($where)
            ->group('a.userid, a.classes_id')
            ->count();

        $rows = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_classes_step_resource b', 'b.id=a.resource_id')
            ->join('o_classes c', 'c.id=a.classes_id')
            ->join('o_members d', 'd.userid=a.userid')
            ->where($where)
            ->field('d.userid, d.name, d.department_name, d.division, c.title, SUM(a.learning_time) as duration, a.add_time as start_time')
            ->group('a.userid, a.classes_id')
            ->order('a.add_time', 'asc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                } else {
                    $v['userid'] = $v['userid'];
                }
            } else {
                $v['userid'] = $v['userid'];
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }

    public function exportClassesRecord(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }


        $get = $request->get();

        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['d.name|d.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['b.courseware_id', '=', $get['id']];
        $where[] = ['a.qiandao', '=', 0];


        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件班级学习记录'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '课程名称', '开始学习时间', '学习时长(s)']);

        $total = Db::table('o_classes_log')
            ->alias('a')
            ->join('o_classes_step_resource b', 'b.id=a.resource_id')
            ->join('o_classes c', 'c.id=a.classes_id')
            ->join('o_members d', 'd.userid=a.userid')
            ->where($where)
            ->group('a.userid, a.classes_id')
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_classes_log')
                ->alias('a')
                ->join('o_classes_step_resource b', 'b.id=a.resource_id')
                ->join('o_classes c', 'c.id=a.classes_id')
                ->join('o_members d', 'd.userid=a.userid')
                ->where($where)
                ->field('d.userid, d.name, d.department_name, d.division, c.title, SUM(a.learning_time) as duration, a.add_time as start_time')
                ->group('a.userid, a.classes_id')
                ->order('a.add_time', 'asc')
                ->limit($start, $nums)
                ->select();

            foreach ($rows as &$v) {
                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $carolid = '00'.$v['userid'];
                    } else {
                        $carolid = $v['userid'];
                    }
                } else {
                    $carolid = $v['userid'];
                }
                $arr = [
                    $carolid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['title'],
                    date('Y-m-d H:i:s',$v['start_time']),
                    $v['duration'],
                ];
                fputcsv($fp, $arr);
            }

        }
        //每1千条数据就刷新缓冲区
        ob_flush();
        flush();
    }


    public function learningRecord(Request $request)
    {
        $id = $request->param('id');

        View::assign('id',$id);

        return View::fetch();
    }

    // 课件E-Learning学习记录
    public function getLearningRecordList(Request $request)
    {
        if (!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();

        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['d.name|d.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['b.courseware_id', '=', $get['id']];


        $total = Db::table('o_learning_log')
            ->alias('a')
            ->join('o_learning_step_resource b', 'b.id=a.resource_id')
            ->join('o_learning c', 'c.id=a.learning_id')
            ->join('o_members d', 'd.userid=a.userid')
            ->where($where)
            ->group('a.userid, a.learning_id')
            ->count();

        $rows = Db::table('o_learning_log')
            ->alias('a')
            ->join('o_learning_step_resource b', 'b.id=a.resource_id')
            ->join('o_learning c', 'c.id=a.learning_id')
            ->join('o_members d', 'd.userid=a.userid')
            ->where($where)
            ->field('d.userid, d.name, d.department_name, d.division, c.title, SUM(a.learning_time) as duration, a.add_time as start_time')
            ->group('a.userid, a.learning_id')
            ->order('a.add_time', 'asc')
            ->page($get['page'], $get['limit'])
            ->select()
            ->toArray();

        foreach ($rows as &$v) {
            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                } else {
                    $v['userid'] = $v['userid'];
                }
            } else {
                $v['userid'] = $v['userid'];
            }
        }

        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }


    public function exportLearningRecord(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }


        $get = $request->get();

        $where = [];

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['d.name|d.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        $where[] = ['b.courseware_id', '=', $get['id']];


        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '课件E-Learning学习记录'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '课程名称', '开始学习时间', '学习时长(s)']);

        $total = Db::table('o_learning_log')
            ->alias('a')
            ->join('o_learning_step_resource b', 'b.id=a.resource_id')
            ->join('o_learning c', 'c.id=a.learning_id')
            ->join('o_members d', 'd.userid=a.userid')
            ->where($where)
            ->group('a.userid, a.learning_id')
            ->count();

        $nums = 100; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;

            $rows = Db::table('o_learning_log')
                ->alias('a')
                ->join('o_learning_step_resource b', 'b.id=a.resource_id')
                ->join('o_learning c', 'c.id=a.learning_id')
                ->join('o_members d', 'd.userid=a.userid')
                ->where($where)
                ->field('d.userid, d.name, d.department_name, d.division, c.title, SUM(a.learning_time) as duration, a.add_time as start_time')
                ->group('a.userid, a.learning_id')
                ->order('a.add_time', 'asc')
                ->limit($start, $nums)
                ->select();

            foreach ($rows as &$v) {
                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $carolid = '00'.$v['userid'];
                    } else {
                        $carolid = $v['userid'];
                    }
                } else {
                    $carolid = $v['userid'];
                }
                $arr = [
                    $carolid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $v['title'],
                    date('Y-m-d H:i:s',$v['start_time']),
                    $v['duration'],
                ];
                fputcsv($fp, $arr);
            }

        }
        //每1千条数据就刷新缓冲区
        ob_flush();
        flush();
    }
}